package cn.sciento.starter.tenant.custom.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.starter.tenant.custom.core.TenantCustomContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE+10000)
public class TenantCustomFilter implements Filter {
  private static final Logger LOGGER = LoggerFactory.getLogger(TenantCustomFilter.class);
  
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}
  
  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
      HttpServletRequest request = (HttpServletRequest)servletRequest;
      String tenantNum = getTenantNum(request);
      if (StringUtils.isNotBlank(tenantNum)) {
        LOGGER.debug("Request url: {} ,  tenantNum: {}", request.getRequestURL(), tenantNum);
        TenantCustomContext.setTenantNum(tenantNum);
      } 
      chain.doFilter(servletRequest, response);
    } finally {
      TenantCustomContext.clear();
    } 
  }
  
  private String getTenantNum(HttpServletRequest request) {
    String tenantNum = request.getHeader("tenantNum");
    if (StringUtils.isBlank(tenantNum)) {
      tenantNum = request.getParameter("tenantNum");
    }
    return tenantNum;
  }
  
  @Override
  public void destroy() {}
}
